using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using CustomCMS.API.ObjectModel;
using System.Text.RegularExpressions;
using System.Globalization;

namespace CustomCMS.API.Wrapper
{
    class FileSystemWrapper
    {
        internal static void CreateDirectory(string location)
        {
            Directory.CreateDirectory(location);
        }

		internal static string GetFileContent(string filename)
		{
			string content = File.ReadAllText(filename, Encoding.UTF8);
			if (Regex.IsMatch(content, @"\r(?!\n)")) SetFileContent(filename, content);
			return Regex.Replace(content, @"\r\n", "\r");
		}

        internal static void SetFileContent(string filename, string content)
        {
            using ( StreamWriter sw = new StreamWriter(filename, false, System.Text.Encoding.UTF8))
            {
                sw.Write(Regex.Replace(content, @"\r", "\r\n"));
                sw.Flush();
                sw.Close();
            }
        }

        internal static void SetFileSummary(string filename, ElementInfo info)
        {
            using( StreamWriter file = File.CreateText(filename + ".fileinfo") )
            {
                file.Write("author=" + info.Author + "\n");
                file.Write("title=" + info.Title + "\n");
                file.Write("comments=" + info.Comment + "\n");
                file.Write("lockedBy=" + info.LockedBy + "\n");
                file.Write("revision=" + info.Revision.ToString() + "\n");
                file.Write("template=" + info.Template + "\n");
                file.Write("date=" + info.Date.ToUniversalTime().ToString("u", DateTimeFormatInfo.InvariantInfo) + "\n");
                file.Write("sectionStates=" + info.SectionStates + "\n");
                file.Flush();
                file.Close();
            }
        }

        internal static ObjectModel.ElementInfo GetFileSummary(string filename, string pathPrefix)
        {
            try
            {
                string infoFilename = Regex.Replace(filename, "\\.\\d+\\.\\d+$|\\.\\d+$", API.Persistance.FileSystemPersistanceProvider.FILEINFO_EXTENSTION+"$0");
                if (infoFilename == filename) infoFilename += API.Persistance.FileSystemPersistanceProvider.FILEINFO_EXTENSTION;
                if (!File.Exists(infoFilename)) return null;

                string text = File.ReadAllText(infoFilename);
                string id = Regex.Replace(filename.Replace(pathPrefix, ""), "^[/\\\\]?root[/\\\\](?:(_history[/\\\\][^/\\\\]+[/\\\\])|[^/\\\\]+[/\\\\])", "$1");
                ElementInfo info = new ElementInfo(id);
                info.Author = GetItem(text, "author");
                info.Title = GetItem(text, "title");
                info.Comment = GetItem(text, "comments");
                info.LockedBy = GetItem(text, "lockedBy");
                info.Template = GetItem(text, "template");
                info.SectionStates = GetItem(text, "sectionStates");

                int.TryParse(GetItem(text, "revision"), out info.Revision);

                DateTime date;
                DateTime.TryParseExact(GetItem(text, "date"), "u", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out date);
                if (date > DateTime.MinValue) info.Date = date.ToLocalTime();

                return info;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static string GetItem(string text, string name)
        {
            Match m = Regex.Match(text, "^" + name + "=(.*)$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            return m.Success ? m.Groups[1].Value : null;
        }
    }
}
